<template>
    <div class="wrapper">
        <NormalTable 
            :refresh-action="'角色查询'"
            :tableColumns="tableColumns" 
            :events="events"
            :tableAttribute = "tableAttribute" 
            ref="childRef">
        </NormalTable>
        <el-button-group class="bg">
            <el-button class="btn" type="primary"  @click="onAdd"
                >增加角色</el-button
            >
            <el-button
                class="btn"
                type="primary"
                
                @click="onDelete"
                >删除角色</el-button
            >
            <el-button
                class="btn"
                type="primary"
                
                @click="onFunc('action')"
                :disable="childRef?.tableRef?.getSelectionRows().length == 1"
                >角色功能</el-button
            >
            <el-button
                class="btn"
                type="primary"
                
                @click="onFunc('user')"
                :disable="childRef?.tableRef?.getSelectionRows().length == 1"
                >角色用户</el-button
            >
        </el-button-group>
    </div>
    <el-dialog
        v-model="dialogRoleVisible"
        title="角色维护"
        draggable
        destroy-on-close
    >
        <Role
            :role="paramRole"
            @yh-newrole="onYhnewrole($event)"
            @yh-updaterole="onYhupdaterole($event)"
            @yh-closedialog="onCloseDialog"
        >
        </Role>
    </el-dialog>
    <el-dialog v-model="dialogRoleFuncVisible" draggable destroy-on-close>
        <template #header>
            <div class="title">{{ roleName }}角色权限维护</div>
        </template>
        <RoleFunc :roleId="paramRoleId" @yh-closedialog="onCloseDialog">
        </RoleFunc>
    </el-dialog>
    <el-dialog v-model="dialogRoleUserVisible" draggable destroy-on-close>
        <template #header>
            <div class="title">{{ roleName }} 角色用户维护</div>
        </template>
        <RoleUsers :roleId="paramRoleId" @yh-closedialog="onCloseDialog">
        </RoleUsers>
    </el-dialog>
    
</template>
<script setup lang="ts" name="SysRoles">
import { ref, toRaw, onMounted } from 'vue';
import { RoleModel } from '@/common/types/model';
import { ElMessage, ElMessageBox } from 'element-plus';
// import { Delete, Plus, Search } from '@element-plus/icons-vue';
import { forEach, findIndex, forEachRight, includes } from 'lodash';
import { tableColumnDefault } from '@/hooks/useTable';
import { Request } from '@/app/request';
import type { QueryItem, TableColumn } from '@/common/types/app';
import Role from './Role.vue';
import RoleFunc from './RoleFunc.vue';
import RoleUsers from './RoleUsers.vue';

import NormalTable from '@/components/tables/NormalTable.vue';
// v-bind:table-data="tableData"
// const tableData = ref<Array<RoleModel>>([]);
const dialogRoleVisible = ref(false);

const dialogRoleFuncVisible = ref(false);
const dialogRoleUserVisible = ref(false);
const tableAdjustHeight = ref(0);

let paramRole: RoleModel | undefined;
const paramRoleId = ref(0);
const roleName = ref('');

// 定义子组件的 ref
const childRef = ref<InstanceType<typeof NormalTable>>();

const tableColumns = ref<Array<TableColumn>>([
    {
        ...tableColumnDefault,
        order: 1,
        prop: 'name',
        label: '角色',
        formFieldItemType: 'input',
        width: 180,
    },
    {
        ...tableColumnDefault,
        order: 2,
        prop: 'remark',
        label: '备注',
        formFieldItemType: 'input',
        width: 200,
    },
]);
const tableAttribute = ref({
    'id': 'roles-table-roles',
    // 'row-key': 'id'
});

onMounted(() => {
    childRef.value?.refresh();
});

const onUpdate = (row: any) => {
    paramRole = toRaw(row);
    dialogRoleVisible.value = true;
};
const onFunc = async (t: string) => {
    const rows: Array<RoleModel> = childRef.value?.tableRef?.getSelectionRows() || [];

    if (rows.length !== 1) {
        ElMessage.info('请选择一条记录');
        return;
    }
    paramRoleId.value = rows[0]['id'] as number;
    roleName.value = rows[0]['name'] as string;
    if (t === 'action') {
        dialogRoleFuncVisible.value = true;
    } else {
        dialogRoleUserVisible.value = true;
    }
};
const onCloseDialog = async (arg: any) => {
    if (dialogRoleVisible.value) {
        dialogRoleVisible.value = false;
    }
    if (dialogRoleUserVisible.value) {
        dialogRoleUserVisible.value = false;
    }

    
};
const onAdd = () => {
    paramRole = undefined;
    dialogRoleVisible.value = true;
};

const onDelete = async () => {
    const rows = childRef.value?.tableRef?.getSelectionRows();
    const names = Array<string>();
    const ids = Array<number>();
    forEach(rows, (v: any) => {
        names.push(v.name);
        ids.push(v.id);
    });
    const msg = names.join(',     ');
    const cr = await ElMessageBox.confirm(msg, '确认删除如下角色', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
    })
        .then(() => {
            return true;
        })
        .catch(() => {
            return false;
        });
    if (cr) {
        //
        const req = new Request('角色删除', { ids });
        const r = await req.post();
        if (r.code > 100) {
            forEachRight(childRef.value?.tableData, (v: any, i: number) => {
                if (includes(ids, v.id)) {
                    childRef.value?.tableData.splice(i, 1);
                }
            });
        }
    }
};
const onYhnewrole = (data: RoleModel) => {
    childRef.value?.tableData.push(data);
};
const onYhupdaterole = (data: RoleModel) => {
    const i = findIndex(childRef.value?.tableData, (o) => {
        return o.id === data.id;
    });
    childRef.value!.tableData[i] = {
        ...data,
    };
};

const events = {
     'row-dblclick': onUpdate
}
</script>
<style lang="scss" scoped>
.bg {
    margin-top: 10px;

    .btn {
        margin-right: 10px;
    }
}
.title {
    text-align: center;
    font-size: larger;
}
</style>
